﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Net
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Reflection;
    using System.Text;

    /// <summary>This is a helper for <see cref="Parser{T}"/>.</summary>
    [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Cannot be static due to use as generic parameter.")]
    internal sealed class ParserHelper
    {
        private const BindingFlags BindNonPublicly = BindingFlags.NonPublic | BindingFlags.Static;
        private const BindingFlags BindPublicly = BindingFlags.Public | BindingFlags.Static;
        private static readonly Type[] ParseParameters = new Type[] { typeof(string) };
        private static readonly Type[] RawParseParameters = new Type[] { typeof(ArraySegment<byte>), typeof(Encoding) };

        internal static MethodInfo GetParseMethod<T>(string name, bool nonPublic)
        {
            return typeof(T).GetMethod(name, nonPublic ? BindNonPublicly : BindPublicly, null, ParseParameters, null);
        }

        internal static MethodInfo GetRawParseMethod<T>(string name)
        {
            return typeof(T).GetMethod(name, BindNonPublicly, null, RawParseParameters, null);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>The parse method when the type to parse is a string.</summary>
        /// <remarks>Should be private. Must be internal, otherwise can't be found via reflection on the phone.</remarks>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called through reflection.")]
        internal static string ParseString(string s)
        {
            return s;
        }

        /// <summary>The raw parse method when the type to parse is a string.</summary>
        /// <remarks>Should be private. Must be internal, otherwise can't be found via reflection on the phone.</remarks>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called through reflection.")]
        internal static string RawParseString(ArraySegment<byte> segment, Encoding encoding)
        {
            return segment.Array == null ? null : encoding.GetString(segment.Array, segment.Offset, segment.Count);
        }
    }
}
